package postgres

import (
	"auth/model"
	"auth/model/entity"
	"gorm.io/gorm"
	"time"
)

var UserJob = &userJob{}
var UserActive = &userActive{}

type userJob struct{}
type userActive struct{}

func (a *userJob) Create(m *entity.UserJob) (int64, error) {
	err := db.Create(m).Error
	return 0, err
}

func (a *userJob) SetUserJobs(userId int64, jobIds []int64) error {
	return db.Transaction(func(tx *gorm.DB) error {
		TxErr := tx.Delete(&[]entity.UserJob{}, "user_id = ?", userId).Error
		if len(jobIds) == 0 {
			return nil
		}
		if TxErr != nil {
			return TxErr
		}
		var useJobs []entity.UserJob
		for _, v := range jobIds {
			useJobs = append(useJobs, entity.UserJob{
				UserId: userId, JobId: v,
			})
		}
		TxErr = tx.Create(&useJobs).Error
		if TxErr != nil {
			return TxErr
		}
		return nil
	})
}

func (a *userJob) DeleteByUserId(id int64) error {
	return db.Delete(&entity.UserJob{}, "user_id=?", id).Error
}

func (a *userJob) CheckJobExistUser(jobId int64) (int64, error) {
	var (
		q     = db.Debug().Model(&entity.UserJob{})
		count int64
		err   error
	)
	err = q.Where("job_id =?", jobId).Count(&count).Limit(1).Error
	return count, err
}

func (a *userJob) List(in *model.UserJobListRequest) (int, []*entity.UserJob, error) {
	var (
		q        = db.Model(&entity.UserJob{})
		err      error
		total    int64
		userJobs []*entity.UserJob
	)

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&userJobs).Error; err != nil {
		return 0, nil, err
	}
	return int(total), userJobs, nil
}

func (a *userActive) Create(m *entity.UserActive) (int64, error) {
	err := db.Create(m).Error
	return 0, err
}
func (a *userActive) Exist(date time.Time) (bool, error) {
	var u entity.UserActive
	err := db.Model(&entity.UserActive{}).Where("year=? and month=? and day=?",
		date.Year(), date.Month(), date.Day()).First(&u).Error
	return u.ID != 0, err
}
